package boogui.admin;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;

import boogui.movie.MovieVO;

public class MovieRegistryService implements IMovieRegistryService {
	
	private File selectedFile = null;
	private MovieRegistryDAO md = null;

	public MovieRegistryService() {	
		md = new MovieRegistryDAO();
	}	
	
	// 이미지 출력
	@Override
	public void showImage(JLabel lbl, JTextField tf) {
		File file = this.fileChooser();
		BufferedImage image = null;
		try {
			image = ImageIO.read(file);		
			Image resizeimg = image.getScaledInstance(145, 208, Image.SCALE_SMOOTH);		
			lbl.setIcon(new ImageIcon(resizeimg));
			tf.setText(file.getAbsolutePath());
		} catch (IOException e) {			
		} catch (IllegalArgumentException ie) {}
	}
	@Override
	public void showImage(JLabel lbl) {
		File file = this.fileChooser();
		BufferedImage image = null;
		try {
			image = ImageIO.read(file);
			Image resizeimg = image.getScaledInstance(230, 300, Image.SCALE_SMOOTH);		
			lbl.setIcon(new ImageIcon(resizeimg));
		} catch (IOException e) {	
		} catch (IllegalArgumentException ie) {}
	}
	
	// 파일열기
	@Override
	public File fileChooser() {		
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
		FileNameExtensionFilter filter = new FileNameExtensionFilter("이미지 파일 (*.jpg; *.png; *.gif)", "png", "jpg", "gif");
		fileChooser.setFileFilter(filter);		

		int result = fileChooser.showOpenDialog(null);
		if (result == JFileChooser.APPROVE_OPTION) {			
			selectedFile = fileChooser.getSelectedFile();				
		}
		//System.out.println(selectedFile);
		return selectedFile;
	}
	
	// 영화 정보 등록
	@Override
	public boolean createMovie(MovieVO m, String path) {
		boolean result = false;
		if (md.insertMovie(m, path)) {
			JOptionPane.showMessageDialog(null, "성공적으로 등록하였습니다.");
			result = true;
		} else {
			JOptionPane.showMessageDialog(null, "영화 정보 등록에 실패하였습니다.", "", JOptionPane.ERROR_MESSAGE);
			result = false;
		}
		return result;
	}
	
	// 숫자만 뽑기
	@Override
	public String extractNum(String str) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < str.length(); i++) {
			if (Character.isDigit(str.charAt(i))) {
				sb.append(str.charAt(i));
			}
		}
		return sb.toString();
	}
	
}
